package com.jinbooks.persistence.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinbooks.entity.marketing.MarketingCampaign;
import com.jinbooks.entity.marketing.MarketingCampaignJob;
import com.jinbooks.persistence.mapper.MarketingCampaignMapper;
import com.jinbooks.persistence.service.MarketingCampaignService;
import com.jinbooks.schedule.ScheduleAdapterBuilder;
import org.quartz.JobDataMap;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 营销活动Service实现类
 */
@Service
public class MarketingCampaignServiceImpl extends ServiceImpl<MarketingCampaignMapper, MarketingCampaign>
        implements MarketingCampaignService {

    @Autowired
    private Scheduler scheduler;

    @Override
    public boolean saveCampaign(MarketingCampaign marketingCampaign) {
        // 设置状态为草稿
        marketingCampaign.setStatus("draft");
        return this.saveOrUpdate(marketingCampaign);
    }

    @Override
    public boolean saveAndExecuteCampaign(MarketingCampaign marketingCampaign) {
        // 设置状态为激活
        marketingCampaign.setStatus("active");
        boolean result = this.saveOrUpdate(marketingCampaign);

        // 如果保存成功，将营销活动加入任务执行队列
        if (result) {
            try {
                scheduleCampaignExecution(marketingCampaign);
            } catch (Exception e) {
                // 如果调度失败，记录日志但不回滚保存操作
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    public IPage<MarketingCampaign> pageList(Page<MarketingCampaign> page, MarketingCampaign marketingCampaign) {
        return baseMapper.selectCampaignPage(page, marketingCampaign);
    }

    @Override
    public MarketingCampaign getCampaignById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public boolean updateCampaign(MarketingCampaign marketingCampaign) {
        return baseMapper.updateById(marketingCampaign) > 0;
    }

    @Override
    public boolean deleteCampaignById(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    public boolean deleteCampaignByIds(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 将营销活动加入任务执行队列
     *
     * @param marketingCampaign 营销活动实体
     * @throws SchedulerException 调度异常
     */
    @Override
    public void scheduleCampaignExecution(MarketingCampaign marketingCampaign) throws Exception {
        // 创建任务数据映射
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("marketingCampaign", marketingCampaign);

        // 判断是否为一次性任务
        boolean isOnce = "once".equals(marketingCampaign.getTaskType());

        if (isOnce) {
            // 一次性任务立即执行
            new ScheduleAdapterBuilder()
                    .setJobClass(MarketingCampaignJob.class)
                    .setScheduler(scheduler)
                    .setJobDataMap(jobDataMap)
                    .setIdentity("marketing_campaign_" + marketingCampaign.getId())
                    .setOnce(true) // 设置为一次性任务
                    .build();
        } else {
            // 根据触发类型确定执行时间
            String cronExpression;
            if ("scheduled".equals(marketingCampaign.getTriggerType()) && marketingCampaign.getScheduledTime() != null) {
                // 定时执行，转换为cron表达式
                cronExpression = dateToCronExpression(marketingCampaign.getScheduledTime());
            } else {
                // 立即执行，使用每秒触发一次的表达式（用于循环任务）
                cronExpression = "0/1 * * * * ?"; // 每秒执行一次
            }

            // 创建调度任务
            new ScheduleAdapterBuilder()
                    .setCron(cronExpression)
                    .setJobClass(MarketingCampaignJob.class)
                    .setScheduler(scheduler)
                    .setJobDataMap(jobDataMap)
                    .setIdentity("marketing_campaign_" + marketingCampaign.getId())
                    .build();
        }
    }

    /**
     * 将日期转换为cron表达式
     *
     * @param date 日期
     * @return cron表达式
     */
    private String dateToCronExpression(java.util.Date date) {
        // 简单实现，实际项目中可能需要更复杂的转换逻辑
        java.util.Calendar cal = java.util.Calendar.getInstance();
        cal.setTime(date);

        int second = cal.get(java.util.Calendar.SECOND);
        int minute = cal.get(java.util.Calendar.MINUTE);
        int hour = cal.get(java.util.Calendar.HOUR_OF_DAY);
        int day = cal.get(java.util.Calendar.DAY_OF_MONTH);
        int month = cal.get(java.util.Calendar.MONTH) + 1; // 月份从0开始
        int year = cal.get(java.util.Calendar.YEAR);

        return String.format("%d %d %d %d %d ? %d", second, minute, hour, day, month, year);
    }
}